package com.atguigu.mymapper;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

/**
 * @author : leimingchao
 * @version V1.0
 * @Project: common_mapper
 * @Package com.atguigu.mymapper
 * @Description: TODO
 * @date Date : 2021年05月24日 20:29
 */
public class MyBatchUpdateProvider extends MapperTemplate {

    public MyBatchUpdateProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * <foreach collection="list" item="record" separator=";" >
     * UPDATE tabple_emp
     * <set>
     * emp_name=#{record.empName},
     * emp_age=#{record.empAge},
     * emp_salary=#{record.empSalary}
     * </set>
     * where emp_id=#{record.empId}
     * </foreach>
     *
     * @param mappedStatement
     */
    public String batchUpdate(MappedStatement mappedStatement) {
        //1.创建StringBuilder用于拼接SQL语句的各个组成部分
        StringBuilder sb = new StringBuilder();
        //2.拼接foreach标签
        sb.append("<foreach collection=\"list\" item=\"record\" separator=\";\" >");
        //3.获取实体类对应的Class对象
        Class<?> entityClass = super.getEntityClass(mappedStatement);
        //4.获取实体类在数据库中对应的表名
        String tableName = super.tableName(entityClass);
        //5.生成update子句
        String updateTable = SqlHelper.updateTable(entityClass, tableName);
        sb.append(updateTable);
        sb.append("<set>");
        String idColumn = null;
        String idColumnHolder = null;
        //6.获取所有字段信息
        for (EntityColumn entityColumn : EntityHelper.getColumns(entityClass)) {
            boolean idPrimaryKey = entityColumn.isId();
            //7.判断当前字段是否为主键
            if (idPrimaryKey) {
                //8.缓存主键的字段名和字段值
                idColumn = entityColumn.getColumn();
                //※返回格式如:#{record.age,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
                idColumnHolder = entityColumn.getColumnHolder("record");
            } else {
                //9.使用非主键字段拼接SET子句
                String column = entityColumn.getColumn();
                String columnHolder = entityColumn.getColumnHolder("record");
                sb.append(column).append("=").append(columnHolder).append(",");
            }
        }
        sb.append("</set>");
        //10.使用前面缓存的主键名和主键值拼接where子句
        sb.append("where ").append(idColumn).append("=").append(idColumnHolder);
        sb.append("</foreach>");
        //11.将拼接好的字符串返回
        return sb.toString();
    }
}
